import { useMessage } from '@hooks/useAppMessage'
import { useNavigate } from '@tanstack/react-router'
import axios from 'axios'

const CSRF_TOKEN_URL = '/sanctum/csrf-cookie'

export const useAxios = () => {
  const navigate = useNavigate()
  const message = useMessage()

  const http = axios.create({
    baseURL: '/api',
    timeout: 6000,
    withCredentials: true, // 跨域请求时是否需要使用凭证
  })

  http.interceptors.request.use(
    (config) => {
      // 在发送请求之前做些什么
      // console.log('请求发送中', config)
      const token = sessionStorage.getItem('token')
      if (token) {
        config.headers['Authorization'] = `Bearer ${JSON.parse(token)}`
      }
      return config
    },
    (error) => {
      // 对请求错误做些什么
      return Promise.reject(error)
    },
  )

  http.interceptors.response.use(
    (response) => {
      // 对响应数据做点什么
      // const { code, msg, data } = response.data
      // if (code === 200 && data?.token) {
      //   sessionStorage.setItem('token', data.token)
      // }
      return response.data
    },
    (error) => {
      console.log('use axios =>', error)
      const { status } = error
      switch (error.status) {
        case 404: {
          navigate({ to: 'Err404' })
          break
        }
        case 403: {
          console.log('Forbidden 权限不足')
          message.error('无操作权限')
          break
        }
        case 401: {
          console.log('TOKEN 失效')
          message.error('登录超时，请重新登录')
          // 跳转到 登录页面
          sessionStorage.removeItem('token')
          sessionStorage.removeItem('admin')
          navigate({ to: '/login' })
          return Promise.reject(error)
        }
      }
      message.error(error.response?.data?.msg || error.message)
      // 对响应错误做点什么
      return Promise.reject(error)
    },
  )
  return { http }
}
